package appapi.mqtt;

import appapi.entity.DeviceDataEntity;
import appapi.service.DeviceDataService;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 请求对象
 *
 * @author luocheng
 * @version 1.0
 * @date 2024/01/15 14:56
 */
@Slf4j
@Component
public class MQTTListener implements ApplicationListener<ContextRefreshedEvent> {

    @Value("${mqtt.username}")
    private String username;
    @Value("${mqtt.password}")
    private String password;
    private final MQTTConnect server;
    private final InitCallback initCallback;

    @Autowired
    private DeviceDataService deviceDataService;
    @Autowired
    public MQTTListener(MQTTConnect server, InitCallback initCallback) {
        this.server = server;
        this.initCallback = initCallback;
    }

    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        try {
            // 设置 MQTT 客户端
            server.setMqttClient(username, password, initCallback);
            // 从数据库中查询设备信息
            List<DeviceDataEntity> list = deviceDataService.list();
            for (DeviceDataEntity deviceDataEntity : list) {
                String deviceName = deviceDataEntity.getDeviceName();
                // 根据设备信息订阅 MQTT 主题
                server.sub("F/+/+/+/+/+/+/+/+/" + deviceName + "/#");
            }
        } catch (MqttException e) {
            log.error(e.getMessage(), e);
        }
    }
}